<?php
    require_once "cache.php";
    require_once "debug.php";

//Get and log URL
$url = $_GET['url'];
debugMsg("PROXY got url     ".$url);

//remove self refs
$selfRef = $IGLocalDir."proxy.php?url=";
$url = str_replace("offline=1&", "", $url);
$url = str_replace("offline=0&", "", $url);
$url = str_replace($selfRef, "", $url);

debugMsg("after replacements ".$url);

//Get cached version offline
$response = "";
if (@$_GET['offline']==1)
{
    debugMsg("Offline mode");
    $response = getCached($url);

//    //Cache resources specifed in a http response if configured
//    if ($response != "")
//    {
//        if ($GLOBALS['forceProxyForResponse'] == true)
//        {
//            //proxy all gadget responses
//            $response = str_replace("http://", $GLOBALS['IGLocalDir']."proxy.php?url=http://", $response);
//            debugMsg("Forcing proxy use in response:\r\n".$response."\r\n");
//        }
//    }

}
//else
if ($response=="")
{
    if (@$_GET['offline']==1)
    {
        debugMsg("No cached resource found - retrieving from web");
    }
    // Open the Curl session
    $session = curl_init($url);

    // Don't return HTTP headers. Do return the contents of the call
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

    // Make the request
    $response = curl_exec($session);

    curl_close($session);

}

$ext = strtolower(substr($url, strlen($url)-3));

switch($ext)
{
    case 'jpg':
    case 'peg':
         header("Content-Type: image/jpg");
         break;
    case 'gif':
        header("Content-Type: image/gif");
        break;
    case 'png':
        header("Content-Type: image/png");
        break;
    case 'htm':
    case 'tml':
        header("Content-Type: text/html");
    case 'xml':
    default:
        break;
}

//Add this to cache if not already there
addToCache($url, $response);




echo $response;
?>
